const { body, query } = require("express-validator");
const mongoose = require("mongoose");
const { id, pageno, pagesize } = require("../common");

const name = (optional = false) => {
    if (optional) {
        return body("name")
            .optional()
            .trim()
            .notEmpty()
            .withMessage("图库名称不能为空")
            .bail()
            .isLength({ min: 1, max: 6 })
            .withMessage("图库名称长度必须在1-6个字符之间");
    }
    return body("name")
        .trim()
        .notEmpty()
        .withMessage("图库名称不能为空")
        .bail()
        .isLength({ min: 1, max: 6 })
        .withMessage("图库名称长度必须在1-6个字符之间");
};

const thumbnail = (optional = false) => {
    if (optional) {
        return body("thumbnail")
            .optional()
            .trim()
            .notEmpty()
            .withMessage("缩略图不能为空")
            .bail()
            .isURL()
            .withMessage("缩略图不能为空");
    }
    return body("thumbnail")
        .trim()
        .notEmpty()
        .withMessage("缩略图不能为空")
        .bail()
        .isURL()
        .withMessage("缩略图不能为空");
};

const categoryId = body("categoryId").custom((value) => {
    if (!value) {
        throw new Error("壁纸分类id不能为空");
    }
    if (!mongoose.Types.ObjectId.isValid(value)) {
        throw new Error("无效的id");
    }
    return true;
});

const isActive = body("isActive")
    .optional()
    .trim()
    .notEmpty()
    .withMessage("是否启用不能为空")
    .bail()
    .isBoolean()
    .withMessage("是否启用只能是布尔值");

module.exports = {
    add: [name(), thumbnail(), categoryId],
    delete: [id],
    update: [id, name(true), thumbnail(true), isActive],
    collections: [id]
};
